<template>
  <el-dialog title="修改密码" :visible.sync="visible" v-if="visible">
    <el-form ref="formRef" :model="formData" :rules="rules" label-postion="right" label-width="100px">
      <el-form-item label="用户名">
        <el-input placeholder="用户名" v-model="formData.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="原密码" prop="oldPassword">
        <el-input type="password" show-password placeholder="原密码" v-model="formData.oldPassword"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input type="password" show-password placeholder="新密码" v-model="formData.password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" show-password placeholder="确认密码" v-model="formData.confirmPassword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="update">提交</el-button>
        <el-button type="warning" @click="visible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
const formData = {
  oldPassword: '',
  password: '',
  confirmPassword: ''
}
export default {
  name: 'UserPassword',
  data () {
    return {
      visible: false,
      formData: { ...formData },
      rules: {
        oldPassword: [{ required: true, message: '原密码不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '新密码不能为空', trigger: 'blur' }],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === this.formData.password) {
                callback()
              } else {
                callback(new Error('两次密码不一致'))
              }
            }
          }
        ]
      }
    }
  },
  methods: {
    init (username) {
      this.visible = true
      this.formData = { ...formData, username }
    },
    update () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.$http.post('admin/user/password', this.formData).then(() => {
            this.$alert('修改成功，请重新登录！', { type: 'success' }).then(() => {
              this.visible = false
              this.$emit('closeWin')
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
